import styles from './index.module.scss'
import Input from './input'
import Button from '../button'
import { useState, useEffect, useRef } from 'react'
import { resetPwd } from '@/api/login'
import { cncryptionCipher } from './encode'

const Index = props => {
  const submitRef = useRef(null)
  const { email, code } = props
  const [pwd1, setPwd1] = useState('')
  const [pwd2, setPwd2] = useState('')
  const [error, setError] = useState({
    pass: true,
    msg: ''
  })

  const pattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/
  // 验证输入密码的合法性
  const isValid = async () => {
    const passd = pattern.test(pwd1)
    if (!passd) {
      return {
        pass: false,
        msg: '密码格式有误!!!'
      }
    }
    if (pwd1 !== pwd2) {
      return {
        pass: false,
        msg: '两次密码不一致!!!'
      }
    }
    return {
      pass: true
    }
  }

  const submit = async () => {
    const errors = await isValid()
    setError(errors)
    if (!errors.pass) {
      return
    }
    const MuId =  localStorage.getItem('MuId')
    const res = await resetPwd({
      code,
      medium: email,
      password: cncryptionCipher(pwd1)
    },{headers:{MuId:MuId ? MuId: undefined}})
    if (!res.code) {
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('email', email)
      window.location.reload()
    }
  }

  useEffect(() => {
    const enterClick = e => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }

    window.addEventListener('keydown', enterClick)
    return () => {
      window.removeEventListener('keydown', enterClick)
    }
  }, [])
  return (
    <div className={styles.resetPwd}>
      <p className={styles.email}>{email}</p>
      <Input placeholder="请输入新密码" type="password" onChange={data => setPwd1(data)} />
      <Input placeholder="请再次输入新密码" type="password" className={styles.pwd} onChange={data => setPwd2(data)} />
      {!error.pass ? <p className={styles.error}>{error.msg}</p> : null}
      <p className={styles.p}>提示：须是6-20个英文字母、数字，且以上两种必须都包含</p>
      <Button hover="opacity" ref={submitRef} onClick={submit} className={styles.btn}>
        确认
      </Button>
    </div>
  )
}

export default Index
